Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Python Functions → *args and **kwargs

Python Functions

*args and **kwargs

In Python, `*args` and `**kwargs` are used in function definitions to allow for flexible argument handling. They enable functions to accept a variable number of positional and keyword arguments, respectively. This enhances code reusability and readability, especially when dealing with functions that might need to interact with different numbers of inputs at different times.

1. *args (Arbitrary Positional Arguments)

`*args` allows a function to accept any number of positional arguments. These arguments are collected into a tuple named `args` (you can choose a different name, but `args` is conventional). Example 1: Basic Usage
Basic `*args` example in Python def my_sum(*args): """Calculates the sum of all numbers passed as positional arguments.""" total = 0 for num in args: total += num return total print(my_sum(1, 2, 3)) print(my_sum(10, 20, 30, 40)) print(my_sum())

Output

6 100 0

Example 2: Combining with Regular Arguments `*args` can be used alongside regular positional arguments. Regular arguments must come *before* `*args`.
Combining with Regular Arguments def greet(greeting, *names): """Greets each person in the names tuple with the given greeting.""" for name in names: print(f"{greeting}, {name}!") greet("Hello", "Alice", "Bob", "Charlie")

Output

Hello, Alice! Hello, Bob! Hello, Charlie!

Example 3: Passing a Tuple Directly You can unpack a pre-existing tuple using the `*` operator when calling a function that uses `*args`.
Passing a Tuple Directly using *args my_tuple = (5, 10, 15) result = my_sum(*my_tuple) # unpacks my_tuple into individual arguments print(result)

Output

30

2. **kwargs (Arbitrary Keyword Arguments)

`**kwargs` allows a function to accept any number of keyword arguments. These arguments are collected into a dictionary named `kwargs` (again, the name is conventional). Example 1: Basic Usage
Python **kwargs (Arbitrary Keyword Arguments) def print_details(**kwargs): """Prints all key-value pairs in the kwargs dictionary.""" for key, value in kwargs.items(): print(f"{key}: {value}") print_details(name="Alice", age=30, city="New York")

Output

name: Alice age: 30 city: New York

Example 2: Combining with Regular and *args `**kwargs` can be combined with regular arguments and `*args`. The order is important: regular arguments, `*args`, then `**kwargs`.
Combining with Regular and *args def describe_person(name, age, *hobbies, **details): print(f"Name: {name}") print(f"Age: {age}") print("Hobbies:", hobbies) # hobbies is a tuple for key, value in details.items(): print(f"{key}: {value}") describe_person("Bob", 25, "reading", "hiking", city="London", occupation="Engineer")

Output

Name: Bob Age: 25 Hobbies: ('reading', 'hiking') city: London occupation: Engineer

Example 3: Passing a Dictionary Directly Similar to `*args`, you can unpack a dictionary using `**` when calling a function that accepts `**kwargs`.
Passing a Dictionary Directly using **kwargs my_dict = {"country": "Canada", "occupation": "Teacher"} print_details(**my_dict) # unpacks my_dict into keyword arguments

Output

country: Canada occupation: Teacher

Important Considerations

Order: The order of parameters in a function definition that uses `*args` and `**kwargs` matters: `regular arguments`, `*args`, `**kwargs`. Flexibility: `*args` and `**kwargs` significantly improve function flexibility. They allow you to write functions that can handle a wide range of inputs without needing to explicitly define every possible parameter. Readability: While powerful, overuse can make code less readable. Use them judiciously when the benefit of flexibility outweighs the potential loss of clarity. By understanding and utilizing `*args` and `**kwargs`, you can create more robust, adaptable, and reusable Python functions. Remember that the names `args` and `kwargs` are conventions, not keywords; you can use different names (e.g., `*my_args`, `**my_kwargs`), but sticking to the convention enhances code readability.

Tutorials